package tt.dz.order.pojo;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;

import tt.dz.order.dao.BaseDAOUtil;
import tt.dz.order.exception.BusinessException;

/**
 * @Title: 报表汇总信息
 * @author 倪波
 * @date 2016-08-08
 */

public class OrderSummaryReport {
	private static Logger log = LoggerFactory.getLogger(OrderSummaryReport.class);

	/**
	 * 金额类型 服务号_卡类型
	 */
	// private String order_type;
	/**
	 * 金额
	 */
	private BigDecimal price;
	/**
	 * 月份 YYYY-MM
	 */
	private String date_m;
	/**
	 * 记录条数
	 */
	private int num;

	/**
	 * 获取最大新一次汇总时间记录信息yyyy-MM 如果没有则返回空null
	 * 
	 * @return
	 */
	public static String queryMaxDate() {
		String sql = "SELECT max(date_m) as date_m from order_summary_report date_m";
		List<Map<String, Object>> list = BaseDAOUtil.queryForList(sql, null);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		} else {
			if (null == list.get(0).get("date_m")) {
				return null;
			} else {
				return list.get(0).get("date_m").toString();
			}

		}
	}

	/**
	 * 根据传入条件查询汇总表order_summary_report中数据,按照年月yyyy-MM汇总计算当月该条件下累计金额数
	 * 
	 * @param cartTyep
	 *            卡类型
	 * @param serverNo
	 *            主服务类型
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @return
	 */
	public static List<OrderSummaryReport> queryOrderSummaryReport(String cartTyep, String serverNo, String startTime,
			String endTime) {
		StringBuilder sql = new StringBuilder(
				" SELECT sum(price) as price,date_m, sum(num) as num  from order_summary_report  where 1=1 ");
		// 卡类型,主服务类型组合查询
		if (!StringUtils.isEmpty(cartTyep) && !StringUtils.isEmpty(serverNo)) {
			sql.append(" and trim(order_type)='" + serverNo + "_" + cartTyep + "' ");
		} else if (!StringUtils.isEmpty(cartTyep)) {
			sql.append(" and trim(order_type) like '%_" + cartTyep + "' ");

		} else if (!StringUtils.isEmpty(serverNo)) {
			sql.append(" and trim(order_type) like '" + serverNo + "_%' ");
		}
		// 时间组合查询
		if (!StringUtils.isEmpty(endTime)) {
			sql.append(" and not trim(date_m)>'" + endTime + "' ");
		}
		if (!StringUtils.isEmpty(startTime)) {
			sql.append(" and not trim(date_m)<'" + startTime + "' ");
		}
		sql.append(" GROUP  BY date_m");
		return BaseDAOUtil.queryForList(sql.toString(), null, OrderSummaryReport.class);
	}

	/**
	 * 从订单信息表order_info中按照serviceNo*cardtype组合汇总该年月对应项金额至汇总表order_summary_report
	 * 
	 * @param datestr
	 *            汇总年月份 YYYY-MM
	 */
	public static void createOrderSummaryReport(String datestr) {
		StringBuilder sql = new StringBuilder("INSERT  INTO order_summary_report (SELECT ");
		sql.append("F.serviceNo||'_'||F.cardtype as order_type,");
		sql.append("sum(F.caculatedTotalPrice) as price,'" + datestr + "' AS date_m ,count(cardtype) as num ");
		sql.append("FROM order_info F ");
		sql.append("WHERE ");
		sql.append("to_char(F.createtime,'YYYY-MM')='" + datestr + "' and F.status='7' GROUP  BY cardtype,serviceNo)");
		BaseDAOUtil.update(sql.toString(), new HashMap<String, Object>());
	}

	/**
	 * 根据月份删除汇总信息
	 * 
	 * @param datestr
	 *            yyyy-MM
	 */
	public static void deleteOrderSummaryReport(String datestr) {
		StringBuilder sql = new StringBuilder("DELETE from order_summary_report WHERE date_m=:date_m");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("date_m", datestr);
		BaseDAOUtil.update(sql.toString(), map);
	}

	/**
	 * 创建汇总信息
	 * 
	 * @throws BusinessException
	 */
	public static void createSummary() throws BusinessException {
		Calendar nowCalendar = Calendar.getInstance();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
		String nowtime = dateFormat.format(nowCalendar.getTime());
		// 查询汇总表order_summary_report中数据最大汇总时间maxtime
		String maxDate = OrderSummaryReport.queryMaxDate();

		if (StringUtils.isEmpty(maxDate)) {
			// maxtime为空,查询order_info中最小时间赋值到maxtime
			String minDate = OrderInfo.queryMinCreateTime().trim();
			if (StringUtils.isEmpty(minDate)) {
				log.error("订单信息为空,不用汇总");
				throw new BusinessException("订单信息为空,不用汇总");
			}
			maxDate = minDate;
		} else {
			maxDate = maxDate.trim();
		}
		if (maxDate.equals(nowtime)) {
			deleteOrderSummaryReport(nowtime);

		}
		try {
			nowCalendar.setTime(dateFormat.parse(nowtime));
			Calendar calendar = Calendar.getInstance();
			Date date = dateFormat.parse(maxDate);
			calendar.setTime(date);
			// 如果当前不等于最大时间这汇总最大时间的下一个月
			if (!maxDate.equals(nowtime)) {
				calendar.add(Calendar.MONTH, 1);
			}
			log.info("calendar:" + dateFormat.format(calendar.getTime()) + "相关报表");
			log.info("nowCalendar:" + dateFormat.format(nowCalendar.getTime()) + "相关报表");
			while (!calendar.after(nowCalendar)) {
				String time = dateFormat.format(calendar.getTime());
				log.info("汇总" + time + "相关报表");
				OrderSummaryReport.createOrderSummaryReport(time);
				calendar.add(Calendar.MONTH, 1);
			}
		} catch (ParseException e) {
			log.error("时间格式化错误:" + e);
		}
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public String getDate_m() {
		return date_m;
	}

	public void setDate_m(String date_m) {
		this.date_m = date_m;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}
}
